package com.company.project.service.impl;

import com.company.project.entity.SysResume;
import org.apache.commons.lang.StringUtils;
import org.mockito.internal.util.StringUtil;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.io.IOUtils;
import com.company.project.entity.FileMsg;
import com.company.project.mapper.ResumeMapper;
import com.company.project.service.FileHandleService;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.FileChannel;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FileHandleImpl implements FileHandleService {
    @Value("${files.uploadDir}")
    String uploadDir;//文件存储根路径
    @Autowired
    private DocumentConverter converter;
    @Autowired
    private ResumeMapper resumeMapper;

    @Override
    public FileMsg fileuploadhandle(MultipartFile file, HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                System.out.println("文件为空");
                return null;
            }
            //获得实体消息
            String fileName = file.getOriginalFilename();
            long fileId = new Date().getTime();
            int ty = fileName.lastIndexOf(".");
            String fileType = null;
            if (ty != -1) {
                fileType = fileName.substring(ty + 1);
            }
            long fileSize = file.getSize();
            Timestamp uploadTime = new Timestamp(fileId);
            //新建子文件夹路径
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileAdd = sdf.format(new Date());
            String path = uploadDir + File.separator + fileAdd + File.separator;
            File pathFile = new File(path);
            if (!pathFile.exists() && !pathFile.isDirectory()) {
                pathFile.mkdirs();
            }
            String realfileName = fileId + "_" + new Random().nextInt(1000) + "_" + fileName;

            String rootUrl = request.getScheme() + "://" + "localhost" + ":" + request.getServerPort() + "/";
            String fileUrl = rootUrl + fileAdd + "/" + realfileName;
            File dest = new File(path, realfileName);
            file.transferTo(dest);// 文件写入
            FileMsg fileMsg = new FileMsg(fileName, fileId, fileUrl, fileType, fileSize, uploadTime);//返回文件消息

            //office文件转pdf
            String preview = generatePDF(fileAdd, realfileName, fileType);
            if (preview != null) {
                fileMsg.setPreviewUrl(rootUrl + "static/web/locale/viewer.html?file=" + preview);
            } else {
                fileMsg.setPreviewUrl(fileUrl);
            }
            return fileMsg;
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return null;
    }

    @Override
    public String generatePDF(String fileAdd, String realfileName, String fileType) {
        if (isOfficeFile(fileType)) {
            File oldfile = new File(uploadDir + File.separator + fileAdd + File.separator, realfileName);
            if (fileType.toLowerCase().equals("txt")) {
                if (!tranTxt(oldfile)) {
                    return null;
                }
            }
            String fileName = realfileName.substring(0, realfileName.lastIndexOf(".")) + ".pdf";
            File newfile = new File(uploadDir + File.separator + "2pdf" + File.separator, fileName);
            if (!newfile.getParentFile().exists()) {
                newfile.getParentFile().mkdirs();
            }
            try {
                if (fileType.toLowerCase().equals("pdf")) {
                    //如果是PDF格式则将文件直接复制一份到新文件夹
                    copy(oldfile, newfile);
                } else {
                    //转换核心代码

                    converter.convert(oldfile).to(newfile).execute();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("转换出错！");
                return null;
            }
            System.out.println("转换成功！");
            return "/2pdf/" + fileName;
        } else {
            return null;
        }

    }

    //将pdf文件复制到另一个文件夹
    public static void copy(File oldFile, File newFile) {
        FileChannel input = null;
        FileChannel output = null;
        try {
            input = new FileInputStream(oldFile).getChannel();
            output = new FileOutputStream(newFile).getChannel();
            output.transferFrom(input, 0, input.size());
        } catch (Exception e) {
            //有错到这儿
        }
    }


    @Override
    public FileMsg scan(MultipartFile file, HttpServletRequest request) {


        try {
            if (file.isEmpty()) {
                System.out.println("文件为空");
                return null;
            }
            //获得实体消息
            String fileName = file.getOriginalFilename();
            long fileId = new Date().getTime();
            int ty = fileName.lastIndexOf(".");
            String fileType = null;
            if (ty != -1) {
                fileType = fileName.substring(ty + 1);
            }
            long fileSize = file.getSize();
            Timestamp uploadTime = new Timestamp(fileId);
            //新建子文件夹路径
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileAdd = sdf.format(new Date());
            String path = uploadDir + File.separator + fileAdd + File.separator;
            File pathFile = new File(path);
            if (!pathFile.exists() && !pathFile.isDirectory()) {
                pathFile.mkdirs();
            }
            String realfileName = fileId + "_" + new Random().nextInt(1000) + "_" + fileName;

            String rootUrl = request.getScheme() + "://" + "localhost" + ":" + request.getServerPort() + "/";
            String fileUrl = rootUrl + fileAdd + "/" + realfileName;
            File dest = new File(path, realfileName);
            file.transferTo(dest);// 文件写入
            FileMsg fileMsg = new FileMsg(fileName, fileId, fileUrl, fileType, fileSize, uploadTime);//返回文件消息
            request.setCharacterEncoding("utf-8");

            String phone = request.getParameter("phone");
            String email = request.getParameter("email");
            String name = request.getParameter("name");

            SysResume sysResume = new SysResume();
            String[] fileU = fileUrl.split("\\.");
            fileUrl=fileU[0]+".pdf";
            sysResume.setUrl(fileUrl);
            sysResume.setPhone(phone);
            sysResume.setEmail(email);
            sysResume.setName(name);
            SysResume obj = resumeMapper.selectExist(phone);//查询手机号是否存在
            if (obj == null&&(sysResume.getPhone()!=null||sysResume.getEmail()!=null)) {
                resumeMapper.saveContent(sysResume);//不存在，进行保存
            } else {
                resumeMapper.addHistory(obj);//将原来的数据添加到历史表
                sysResume.setId(obj.getId());
                resumeMapper.updates(sysResume);//更新现有数据
            }


            //office文件转pdf
            String preview = generatePDF(fileAdd, realfileName, fileType);
            if (preview != null) {
                fileMsg.setPreviewUrl(rootUrl + "static/web/locale/viewer.html?file=" + preview);
            } else {
                fileMsg.setPreviewUrl(fileUrl);
            }
            return fileMsg;
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return null;
    }


    /**
     * @param : [fileType]
     * @return : boolean
     * @throws :
     * @Description ：简单判断是否是office文件
     * @author : lj
     * @date : 2020-2-16 14:21
     */
    private boolean isOfficeFile(String fileType) {
        fileType = fileType.toLowerCase();
        switch (fileType) {
            case "txt":
            case "doc":
            case "docx":
            case "xls":
            case "xlsx":
            case "ppt":
            case "pptx":
            case "pdf":
            case "html":
            case "xml":
                return true;
        }
        return false;
    }

    /**
     * @param : [file]
     * @return : boolean
     * @throws :
     * @Description : TXT文件编码转换，解决转pdf中文乱码问题
     * @author : lj
     * @date : 2020-2-17 0:00
     */
    private boolean tranTxt(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "GBK");
            BufferedReader br = new BufferedReader(isr);
            String OriStr;
            StringBuilder stringBuilder = new StringBuilder();
            while ((OriStr = br.readLine()) != null) {
                //手动拼接换行符
                OriStr += "\n";
                stringBuilder.append(OriStr);
            }
            String targetStr = stringBuilder.toString();
            //false代表不追加直接覆盖,true代表追加文件
            FileOutputStream fos = new FileOutputStream(file, false);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write(stringBuilder.toString());
            osw.flush();
            osw.close();
            fos.close();
            br.close();
            isr.close();
            fis.close();
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }

    }
}



